package net.java.nioserver.sio;

import net.java.nioserver.utils.ChannelUtil;

import java.nio.channels.SocketChannel;
import java.util.HashSet;
import java.util.Set;

/**
 * @author Leonid Shlyapnikov
 */
public class SocketChannelContainer {

    private final Set<SocketChannel> socketChannelSet;

    public SocketChannelContainer(int initialCapacity) {
        this.socketChannelSet = new HashSet<SocketChannel>(initialCapacity);
    }

    public void add(SocketChannel socketChannel) {
        boolean newElement = this.socketChannelSet.add(socketChannel);
        if (!newElement) {
            throw new IllegalArgumentException("Already contains socketChannel: " + socketChannel);
        }
    }

    public void cancel(SocketChannel socketChannel) {
        boolean removed = socketChannelSet.remove(socketChannel);
        if (!removed) {
            throw new IllegalArgumentException("Does not contain socketChannel: " + socketChannel);
        }

        ChannelUtil.close(socketChannel);
    }
}
